
var JWidgetOption = {
  "_id":null,
  baseUrl:'',
  autosave:false,
  saveUrl:null,
  saveCallback:null,
  buttons:[],
  prefix : 'mr_',
  
  fields:{tag : 'div'},
  styles:{
    width:'300px',
    height:'300px',
    left:'50px',
    top:'50px',
    // 'background-color':'transparent',
    'border-color':'#eee',
    opacity:1,
    position: 'absolute',
    'border-style': 'solid'
  },
  /**
   * 微博绑定的信息
   */
//  bindInfo:null,
//  bindUrl:'',
  bindInfo:null,
  configItems:[],
  isEdit:false

};

/**
 * 
 * @param options
 * styles:{}
 * buttons:[{src:'abc.png',events:{click:funciton(){},}}]
 * @return
 */
function JWidget(options){

  this.options= jQuery.extend(true,{}, JWidgetOption, options);
  this.init();
  this.run();
}
/**
 * 功能初始化.
 */
JWidget.prototype.init = function(){
  //check jquery.
  if(typeof $ != 'function'){
    throw new Error("jQuery is required.");
  } 
   
  this.styles = this.options.styles;
  this.fields = this.options.fields;
  
  //Save class name
  this.fields.jClass = this.getClassName();
  //生成ID
//  this.id = this.getId();
  this.id = this.options._id;
  
  var me = this;
  
  /*
   *保存按钮
   * always show
   */
   if(this.options.autosave != true){
    var saveButton = $('<input/>').attr('type','button').addClass('saveBar greenBar').attr('value','保存').css({border:0,height:'13px'})  ;
    this.options.buttons.unshift(saveButton);
    saveButton.click(function(){
      me.save(true);
    });
   }
   
   /*
    * 删除
    */
  var deleteButton = $('<input/>').attr('type','button').addClass('deleteBar greenBar').attr('value','删除').css({border:0,height:'13px'})  ;
  this.options.buttons.unshift(deleteButton);
  deleteButton.click(function(){
    me.del();
  });
  
  this.initConfigBar();
};
//
//JWidget.prototype.maxId = 0; 
//
//JWidget.prototype.getId = function(){
//  if(this.fields.id){
//    JWidget.prototype.maxId = this.fields.id.split('_')[1];
//  }else{
//    this.fields.id = JWidgetOption.prefix+ (++JWidget.prototype.maxId);
//  }
//  return this.fields.id;
//  
//};
/**
 * 功能方法. 在这里添加相应功能
 */
JWidget.prototype.run = function(){
  
  //生成HTML控件.
  this.dom = $(document.createElement('div')).addClass('jwidget').appendTo($('body'));
  
  this.core = $(document.createElement(this.fields.tag)).addClass('core').css({width:'100%',height:'100%'});
  
  this.dom.append(this.core );
  
  this.render();
  
  if(this.options.isEdit)
    this.editInit();

};
JWidget.prototype.editInit = function(){
    
  var me = this;
  this.toolbar();
  
  /*
   * 激活
   */
  this.dom.mouseover(function(event){
    //unactive others
    $('.jwidget.jactive').removeClass('jactive');
    
    me.dom.addClass('jactive');
    
    //设置按钮跟踪鼠标
    
    
    });
   
  /*
   * 可移动事件.
   */
  this.dom.draggable({ containment: 'window' });
  this.dom.draggable( "option", "handle", this.dom.find('.dragBar') );
  this.dom.bind( "dragstop",function(event, ui){
    me.style('left', ui.position.left+'px');
    me.style('top',ui.position.top+'px');
    
    me.draged(event, ui);
    
  });
  this.dom.bind( "drag",function(event, ui){
    me.move(event, ui);
  });
  
  /*
   * Resize事件
   */
  this.dom.resizable();
  this.dom.bind( "resizestop",function(event, ui){
    me.style('width', ui.size.width+'px');
    me.style('height',ui.size.height+'px');

    me.resized(event, ui);
     
  });
  
  /**
   * 注册事件
   */
  this.dom.click(this.click);
  this.load();
};

/**
 * 渲染CSS
 */
JWidget.prototype.render = function(){
       
   this.dom.css( this.styles ); 
    
};

/**
 * 控件上的工具按钮[拖运按钮,保存按钮.]
 */
JWidget.prototype.toolbar = function(){
  $toolBar =  $('<div/>').addClass('toolbar').css({position:'absolute',right:0,top:0,padding:'3px','z-index':'999'}).prependTo(this.dom);
  
  var me = this; 
  var $style = {height:'13px',margin:'3px','float':'right',right:0,top:0,cursor:'pointer'};
  
   
  /*
   * 拖动按钮
   */
  var dragButton = $('<img/>').addClass('dragBar').attr('src',JWidgetOption.baseUrl+'/images/bar_drag.png');
    dragButton.css($style).appendTo($toolBar);
  
    
  /*
   * 配置按钮
   */
   var configButton = $('<img/>').addClass('configBar').attr('src',JWidgetOption.baseUrl+'/images/bar_config.png')
   .click(function(){me.config();});
   configButton.css($style).appendTo($toolBar);
   
   
   
    //add button
    if(this.options.buttons.length>0){
      
      var $style = {width:'30px',height:'15px',margin:'3px',cursor:'pointer'};
  
//      me.configBox.append('<hr/>');
        
      for(var i in this.options.buttons){
        var button = this.options.buttons[i];
        button.css($style).appendTo($toolBar);
      }
    }
  
};

/**
 * 
 */
JWidget.prototype.changed = function(changed){
  
  var me = this;
  if(changed == true){ //reset
    if(this.options.autosave == true){
      me.save();
      return;
    }
    this.dom.find('input.saveBar').css({color:'#fff'}).bind('click',function(){me.save();});
  }else{
    this.dom.find('input.saveBar').css({color:'#333'}).unbind('click');
  }
  
};
/**
 * 返回需要保存的数据
 */

JWidget.prototype.field = function(key,value){
  return this.attributes('fields',key,value);
};
JWidget.prototype.style = function(key,value){
  return this.attributes('styles',key,value);
};
JWidget.prototype.attributes = function(type,key,value){
  
  if(typeof type == 'undefined'){
    var data = {};
    data.id = this.id;
    data.fields = this.fields;
    data.styles = this.styles;
    
    return data;
  }else if(typeof value == 'undefined'){
    if(typeof key == 'object'){//set with {}
      this[type] = $.extend(this[type],key);
      this.changed(true);
    }
    else
      return this[type][key];//get
    
  }else if(typeof key == 'string'){//set
    
    this[type][key] = value;
    this.changed(true);
  }
  
  
};
/**
 * 上传数据到服务器
 */
JWidget.prototype.save = function(force){ 
  if(!this.beforeSave()){
    return;
  }
  if(this.options.saveUrl){
    $delay = 3000;
    if(this.options.timeoutPid){
      clearTimeout(this.options.timeoutPid);
      this.options.timeoutPid = null;
    }
    var me = this;
    if(force == true){
      $delay = 0;
    }
    this.options.timeoutPid = setTimeout(function(){
      $.post(me.options.saveUrl,me.attributes(),function(data,status){
        me.id = data.id;
        me.options.timeoutPid = null;
        if(typeof me.options.saveCallback == 'function'){
          me.options.saveCallback(data,status);
        }
        me.changed(false);
        
        if(force == true){//关闭窗口.
          
          $('div.configBox').dialog('destroy').remove();
        }
      },'json');
    },$delay);
    
  }
  
};

JWidget.prototype.del = function(){ 
  
  var me = this;
    
  var confrm = confirm("你确定要删除吗?");
  if(confrm){
    
    if(this.options.timeoutPid){
      clearTimeout(this.options.timeoutPid);
      this.options.timeoutPid = null;
    }
    $.post(this.options.saveUrl,{op:'del',id:this.id},function(data,status){
        
        if(status == 'success'){
          me.dom.remove();
          if(me.configBox)
            me.configBox.remove();
        }
      });
  }
};

/************************
 * 事件处理,当
 * **********************/

/*
 * 事件
 */
JWidget.prototype.resized = function(event, ui){};
JWidget.prototype.draged = function(event, ui){};
JWidget.prototype.move = function(event, ui ){}; 
JWidget.prototype.click = function(){}; 
JWidget.prototype.load = function(){};
JWidget.prototype.beforeSave = function(){ return true;};
  
 

/************************
 * 设置处理
 * **********************/

JWidget.prototype.initConfigBar = function(){
  var me = this;
  
  var sliderOption = {
    
    min:0,
    max:9,
    slide:function(event, ui){
        $name =  $(this).attr('name');
        $($name.split(' ')).each(function(i,$name){
          me.style($name, ui.value+'px');
          me.dom.css($name,  ui.value+'px'); 
          me.core.css($name,  ui.value+'px'); 
        });
      }
  };
  var opacityrOption  = {
    value:10,
    min:1,
    max:10,
    slide:function(event, ui){
      rate = 0.1;
        $name =  $(this).attr('name');
        me.style($name,rate * ui.value) ;
        me.dom.css($name, rate * ui.value ); 
        me.core.css($name, rate * ui.value ); 
      }
  };
  
  var noBackBtn = $('<div/>').append($('<input/>').attr('type','checkbox').click(function(){
              if($(this).attr('checked') == true){
                cssKey = 'background-color';
                me.dom.css(cssKey, ''); 
//                noBackBtn.css('background-color', '#fff' );
                delete me.styles[cssKey];  
//                me.style('background','transparent') ;
                me.style(cssKey,'transparent') ;
              }
              })).append('无色');
  
  items = {
    背景色:[$('<div><div/>').addClass('colorbutton').click(function(){$(this).next().find('input:checkbox').attr('checked',false);me.pickerColor(this,'background-color');}),
        noBackBtn
        ],
    透明度:[$('<div></div>').addClass('slider').attr('name','opacity').slider( opacityrOption )],
    边框: [$('<div></div>').addClass('slider').attr('name','border-width').slider(sliderOption),
        $('<div><div/>').addClass('colorbutton').click(function(){me.pickerColor(this,'border-color');})],
    页边距:[$('<div></div>').addClass('slider').attr('name','padding').slider($.extend(true,{},sliderOption,{max:30}))],
    圆角:[$('<div></div>').addClass('slider').attr('name','border-radius -moz-border-radius -webkit-border-radius').slider(sliderOption)]
    
  };
  
  this.defaultConfigItems = items;
  this.configItems = $.extend(true,{},this.options.configItems);
  
  
};
JWidget.prototype.config = function(){
//  alert('config');
//  $('div.configBox').dialog('destroy').remove();
  if(!this.configBox){
    this.configBox = $("<div></div>").addClass('configBox').css({opacity:1});
      
    this.configBox.text('');
    
    var me = this;
    $.map(this.configItems,function(obj){
      me.configBox.append(obj);
    });
    
  
    $.each(this.defaultConfigItems,function(label,obj){
      row = $('<div></div>').addClass('row').addClass('default');
      if(typeof label != 'number'){
        row.append($('<div></div>').addClass('label').text(label));
      } 
  
      if(typeof me.defaultConfigItems[label] == 'object' ){
        $.map(me.defaultConfigItems[label],function(item){row.append(item);});
      } 
      me.configBox.append(row);
      
    });
//    
//    //add button
//    if(this.options.buttons.length>0){
//      
//      var $style = {width:'50px',height:'30px',margin:'3px',cursor:'pointer'};
//  
//      me.configBox.append('<hr/>');
//        
//      for(var i in this.options.buttons){
//        var button = this.options.buttons[i];
//        button.css($style).appendTo(me.configBox);
//      }
//    }
    
  }
  this.configBox.dialog({modal:true});
};


JWidget.prototype.pickerColor = function(button,cssKey){
  button = $(button); 

  var dcolor = this.style[cssKey];
  this.dom.css(cssKey, dcolor);
   
  var me = this;
  options = {
    color : '#'+dcolor,
    onShow : function(colpkr) {
//      $(colpkr).fadeIn(500);
      return true;
    },
    onHide : function(colpkr) {
      $(colpkr).fadeOut(500);
      return false;
    },
    onChange : function(hsb, hex, rgb) {
     
      me.dom.css(cssKey, '#' + hex); 
      button.css(cssKey, '#' + hex);
      // button.css('background-color', '#' + hex);
      me.style(cssKey, '#' + hex);  
    },
    onSubmit : function(hsb, hex, rgb) {
      button.ColorPickerHide();
    }
  };
  button.ColorPicker(options);
  button.ColorPickerShow();

};

JWidget.prototype.getClassName = function() { 
  obj = this;
  if (typeof obj != "object" || obj === null)
    return false;
  else
    return /(\w+)\(/.exec(obj.constructor.toString())[1];
   
};  
